package com.example.taskmanager;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.util.Callback;
import javafx.animation.FadeTransition;
import javafx.util.Duration;
import javafx.scene.control.Alert.AlertType;

import java.util.List;

public class MainController {
    @FXML
    private TextField taskName;
    @FXML
    private TextField taskDescription;
    @FXML
    private DatePicker taskDueDate;
    @FXML
    private TextField taskGroupName;
    @FXML
    private ListView<Task> taskListView;
    @FXML
    private Button filterButton;
    @FXML
    private ChoiceBox<String> filterChoiceBox;
    @FXML
    private VBox groupButtonsBox;
    @FXML
    private Button addTaskButton;

    private ObservableList<Task> tasks;
    private Button selectedGroupButton;

    @FXML
    public void initialize() {
        tasks = FXCollections.observableArrayList();
        taskListView.setItems(tasks);
        loadTasks();
        taskListView.setCellFactory(new Callback<>() {
            @Override
            public ListCell<Task> call(ListView<Task> listView) {
                return new TaskListCell();
            }
        });

        initFilterChoiceBox();
        updateGroupButtons();

        addTaskButton.getStyleClass().add("add-button");
        filterButton.getStyleClass().add("button");
    }

    private void updateGroupButtons() {
        groupButtonsBox.getChildren().clear();
        List<String> groupNames = TaskManager.getAllGroupNames();
        for (String groupName : groupNames) {
            Button groupButton = new Button(groupName);
            groupButton.getStyleClass().add("group-button");
            groupButton.setMaxWidth(Double.MAX_VALUE); // 设置按钮宽度填满VBox
            groupButton.setOnAction(e -> handleGroupButtonClick(groupButton, groupName));
            groupButtonsBox.getChildren().add(groupButton);
        }
    }

    private void handleGroupButtonClick(Button groupButton, String groupName) {
        if (selectedGroupButton != null) {
            selectedGroupButton.getStyleClass().remove("selected-group-button");
        }
        groupButton.getStyleClass().add("selected-group-button");
        selectedGroupButton = groupButton;

        List<Task> tasks = TaskManager.getTasksByGroupName(groupName);
        taskListView.getItems().setAll(tasks);
    }

    private void initFilterChoiceBox() {
        filterChoiceBox.setItems(FXCollections.observableArrayList("所有任务", "未完成任务", "已完成任务", "今天的任务", "本周的任务"));
        filterChoiceBox.setValue("所有任务");

        filterButton.setOnAction(event -> {
            String filterOption = filterChoiceBox.getValue();
            switch (filterOption) {
                case "未完成任务":
                    tasks.setAll(TaskManager.getIncompleteTasks());
                    break;
                case "已完成任务":
                    tasks.setAll(TaskManager.getCompletedTasks());
                    break;
                case "今天的任务":
                    tasks.setAll(TaskManager.getTasksDueToday());
                    break;
                case "本周的任务":
                    tasks.setAll(TaskManager.getTasksDueThisWeek());
                    break;
                default:
                    loadTasks();
                    break;
            }
        });
    }

    @FXML
    private void handleAddTask() {
        String name = taskName.getText();
        String dueDate = (taskDueDate.getValue() != null) ? taskDueDate.getValue().toString() : "";
        String groupName = taskGroupName.getText();

        if (name.isEmpty() || dueDate.isEmpty() || groupName.isEmpty()) {
            Alert alert = new Alert(AlertType.WARNING);
            alert.setTitle("输入错误");
            alert.setHeaderText(null);
            alert.setContentText("请填写所有必填字段！");
            alert.showAndWait();
            return;
        }

        String description = taskDescription.getText();

        TaskManager.insertTask(name, description, dueDate, groupName);
        loadTasks();
        clearFields();
        updateGroupButtons();

        FadeTransition fadeIn = new FadeTransition(Duration.millis(500), taskListView);
        fadeIn.setFromValue(0.0);
        fadeIn.setToValue(1.0);
        fadeIn.play();
    }

    private void clearFields() {
        taskName.clear();
        taskDescription.clear();
        taskDueDate.setValue(null);
        taskGroupName.clear();
    }

    private void loadTasks() {
        List<Task> taskList = TaskManager.getAllTasks();
        tasks.setAll(taskList);
    }

    @FXML
    private void handleDeleteTask(Task task) {
        TaskManager.deleteTask(task.getId());
        loadTasks();
    }

    @FXML
    private void handleFilterByGroupName() {
        String groupName = taskGroupName.getText().trim();
        if (!groupName.isEmpty()) {
            List<Task> filteredTasks = TaskManager.getTasksByGroupName(groupName);
            tasks.setAll(filteredTasks);
        } else {
            loadTasks();
        }
    }

    private class TaskListCell extends ListCell<Task> {
        private Button toggleStatusButton = new Button();
        private Button deleteButton = new Button("删除");

        public TaskListCell() {
            toggleStatusButton.getStyleClass().add("toggle-button");
            deleteButton.getStyleClass().add("delete-button");
        }

        @Override
        protected void updateItem(Task task, boolean empty) {
            super.updateItem(task, empty);
            if (task != null) {
                setText(task.toString());

                // Set style class based on task status
                if (task.getStatus().equals("未完成")) {
                    getStyleClass().setAll("task-uncompleted");
                } else {
                    getStyleClass().setAll("task-completed");
                }

                toggleStatusButton.setText(task.getStatus().equals("未完成") ? "标记为完成" : "标记为未完成");
                toggleStatusButton.setOnAction(event -> {
                    String newStatus = task.getStatus().equals("未完成") ? "完成" : "未完成";
                    TaskManager.updateTaskStatus(task.getId(), newStatus);
                    task.setStatus(newStatus);
                    setText(task.toString());
                    toggleStatusButton.setText(newStatus.equals("未完成") ? "标记为完成" : "标记为未完成");

                    // Update style class when status changes
                    getStyleClass().setAll(newStatus.equals("未完成") ? "task-uncompleted" : "task-completed");
                });

                deleteButton.setOnAction(event -> {
                    TaskManager.deleteTask(task.getId());
                    loadTasks();
                });

                HBox buttonsBox = new HBox(toggleStatusButton, deleteButton);
                setGraphic(buttonsBox);
            } else {
                setText(null);
                setGraphic(null);
            }
        }
    }
}
